package com.easylinkin.linkappapi.openapi.common;

import com.easylinkin.linkappapi.common.constant.CommonConstant;
import com.easylinkin.linkappapi.common.constant.CommonConstant.ResultCode;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MissingServletRequestParameterException;

/**
 * 通用返回对象 openApi 接口用到
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class CommonResult<T> {
    private String code;
    private String message;
    private T data;

    protected CommonResult() {
    }

    protected CommonResult(String code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public CommonResult(String code, String message) {
        this.code = code;
        this.message = message;
    }

    /**
     * 成功返回结果
     *
     * @param data 获取的数据
     */
    public static <T> CommonResult<T> success(T data) {
        return new CommonResult<T>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data);
    }
    /**
     * 成功返回结果
     *
     */
    public static <T> CommonResult<T> success() {
        return new CommonResult<T>(CommonConstant.ResultCode.SUCCESS.getCode(), CommonConstant.ResultCode.SUCCESS.getMessage());
    }

    /**
     * 失败返回结果
     *
     * @param data 数据
     */
    public static <T> CommonResult<T> failed(T data) {
        return new CommonResult<>(ResultCode.PARAM_ERROR.getCode(), ResultCode.PARAM_ERROR.getMessage(), data);
    }

    public static CommonResult failed(BusinessException e) {
        return new CommonResult(e.getErrorCode(), e.getMessage(), e.toString());
    }

    public static CommonResult failed(Exception e) {
        if (e instanceof BusinessException) {
            BusinessException be = (BusinessException) e;
            return new CommonResult(be.getErrorCode(), be.getMessage(), be.toString());
        }
        if (e instanceof IllegalArgumentException || e instanceof HttpMessageNotReadableException || e instanceof MissingServletRequestParameterException) {
            return new CommonResult(ResultCode.PARAM_ERROR.getCode(), e.getMessage(), e.toString());
        }
        return new CommonResult(ResultCode.SYSTEM_ERROR.getCode(), e.getMessage(), e.toString());
    }

//    public String getCode() {
//        return code;
//    }
//
//    public void setCode(String code) {
//        this.code = code;
//    }
//
//    public String getMessage() {
//        return message;
//    }
//
//    public void setMessage(String message) {
//        this.message = message;
//    }
//
//    public T getData() {
//        return data;
//    }
//
//    public void setData(T data) {
//        this.data = data;
//    }
}

